Compile Lua script into bytecode

Latest update: March 2018

In this tutorial we will show you how to compile Lua script into bytecode. By compiling with bytecode, you can obfuscate the Lua script stored in FlashAir.

Introduction

  1. Place HelloWorld.lua used in the Running Lua on your FlashAir! to FlashAir.
  2. Please refer to Running Lua on your FlashAir! and specify the Lua script execution method in the CONFIG file.

Compile

Create a Lua script to compile the Lua script into bytecode. Use Lua standard function string.dump .

/CompileToByteCode.lua

function luac_func(filename)
  local targets = filename
  local chunk = assert(loadfile(filename))
  local out = assert(io.open(targets..".out", "wb"))
  out:write(string.dump(chunk))
  out:close()
end                
luac_func("HelloWorld.lua")

After executing this script, unmount the card and reinsert it, the HelloWorld.lua.out file will be created.

Execute byte-coded Lua file

If you keep the same file name, this process may not work correctly, so try changing HelloWorld.lua to _HelloWorld.lua. You should also change HelloWorld.lua.out to HelloWorld.lua (the original file name). After those changes, the file is ready to be executed.

We also need to create a Lua script that calls byte-coded files. It is also possible to use dofile from the Lua standard functions to execute this.

/ExecuteByteCode.lua

dofile("/HelloWorld.lua")

If you save this script, unmount the card, reinsert it and run it, the result of bytecode HelloWorld.lua will be displayed. This is similar to Running Lua on your FlashAir!.

Use functions and objects in byte-coded files

Let's try calling the byte-coded Lua file from a different Lua file. First, we create a Lua script that returns a table object.

/ReturnTable.lua

local function _foo()
  print("Hello World!")
end                 
return {
  foo=_foo
}

When using functions and objects in other files, use the require of Lua standard function and read the file. We also create a caller's Lua script.

/CallByteCode.lua

local script = require "ReturnTable"
script.foo()

Compile ReturnTable.lua and bytecode it. After unmounting the card and reinserting it, if you execute CallByteCode.lua, "Hello World!" Will be displayed.

Sample code

View repository (GitHub)

All sample code on this page is licensed under BSD 2-Clause License